package com.tuliyou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tuliyou.common.util.Result;
import com.tuliyou.dto.PageInfo;
import com.tuliyou.dto.UniversityDTO;
import com.tuliyou.entity.University;
import com.tuliyou.mapper.UniversityMapper;
import com.tuliyou.service.UniversityService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UniversityServiceImpl extends ServiceImpl<UniversityMapper, University> implements UniversityService {

    @Resource
    private UniversityMapper universityMapper;

    @Override
    public Result<PageInfo<UniversityDTO>> getUniversities(Integer page, Integer size, String name, String province, String city, String level, String attribute) {
        // 设置分页参数
        PageHelper.startPage(page, size);
        // 执行查询
        List<University> universityList = universityMapper.getUniversities(name, province, city, level, attribute);
        // 关键：先将查询结果强转为Page<University>，保留分页信息
        Page<University> universityPage = (Page<University>) universityList;
        // 转换DTO：基于原始Page的list进行stream映射（不破坏分页信息）
        List<UniversityDTO> universityDTOList = universityPage.stream().map(UniversityDTO::fromUniversity).toList();
        // 封装PageInfo对象
        PageInfo<UniversityDTO> pageInfo = new PageInfo<>();
        pageInfo.setCurrent(universityPage.getPageNum()); // 当前页码
        pageInfo.setSize(universityPage.getPageSize()); // 每页条数
        pageInfo.setTotal(universityPage.getTotal()); // 总记录数
        pageInfo.setPages(universityPage.getPages()); // 总页数
        pageInfo.setRecords(universityDTOList); // 当前页DTO列表
        return Result.success(pageInfo);
    }

    @Override
    public Result<UniversityDTO> getUniversityDetail(String universityCode) {
        University university = universityMapper.getUniversityDetail(universityCode);
        UniversityDTO universityDTO = UniversityDTO.fromUniversity(university);
        return Result.success(universityDTO);
    }
}
